// hotel-management-frontend/src/client/History.js

import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Table, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { clientAPI } from '../services/api'; // Correct: Named import
import moment from 'moment';

const ClientHistory = () => {
    const [form] = Form.useForm();
    const [checkins, setCheckins] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const handleQuery = async (values) => {
        if (!values.idCard) {
            message.warning('请输入身份证号');
            return;
        }
        setLoading(true);
        setCheckins([]);
        setError(null);
        try {
            // Correct API call: Call the specific function on clientAPI
            const response = await clientAPI.getCheckinsByGuestCard(values.idCard);
            setCheckins(response.data);
            if (response.data.length === 0) {
                message.info('未找到入住记录');
            } else {
                message.success(`已找到 ${response.data.length} 条入住记录`);
            }
        } catch (err) {
            console.error('查询入住记录失败:', err);
            setError('查询入住记录失败: ' + (err.response?.data?.message || err.message || '未知错误'));
            message.error(err.response?.data?.error || '查询失败，请检查身份证号或网络连接');
        } finally {
            setLoading(false);
        }
    };

    const checkinColumns = [
        // ... (columns remain the same)
        { title: '房间号', dataIndex: 'room_number', key: 'room_number' },
        { title: '房间类型', dataIndex: 'room_type', key: 'room_type' },
        { title: '房间单价 (¥/天)', dataIndex: 'room_price', key: 'room_price',
            render: (text) => `¥${parseFloat(text).toFixed(2)}`
        },
        { title: '入住时间', dataIndex: 'checkin_date', key: 'checkin_date',
            render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
        },
        { title: '退房时间', dataIndex: 'checkout_date', key: 'checkout_date',
            render: (text) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : 'N/A'
        },
        { title: '状态', dataIndex: 'status', key: 'status' },
        { title: '总金额 (¥)', dataIndex: 'total_amount', key: 'total_amount',
            render: (text) => text !== null ? `¥${parseFloat(text).toFixed(2)}` : 'N/A'
        },
    ];

    const ExpandedConsumptionRow = ({ checkinId }) => {
        const [consumptions, setConsumptions] = useState([]);
        const [subLoading, setSubLoading] = useState(false);

        useEffect(() => {
            const fetchConsumptions = async () => {
                setSubLoading(true);
                try {
                    // Correct API call: Call the specific function on clientAPI
                    const response = await clientAPI.getConsumptionsByCheckinId(checkinId);
                    setConsumptions(response.data);
                } catch (error) {
                    console.error('获取消费记录失败:', error);
                    message.error('获取消费记录失败');
                } finally {
                    setSubLoading(false);
                }
            };
            fetchConsumptions();
        }, [checkinId]);

        const consumptionColumns = [
            // ... (columns remain the same)
            { title: '消费项目', dataIndex: 'item_name', key: 'item_name' },
            { title: '数量', dataIndex: 'quantity', key: 'quantity' },
            { title: '金额 (¥)', dataIndex: 'amount', key: 'amount',
                render: (text) => `¥${parseFloat(text).toFixed(2)}`
            },
            { title: '消费时间', dataIndex: 'consume_time', key: 'consume_time',
                render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
            },
        ];

        return (
            <Table
                columns={consumptionColumns}
                dataSource={consumptions}
                rowKey="consumption_id"
                pagination={false}
                loading={subLoading}
                size="small"
                style={{ margin: '10px 0' }}
                locale={{ emptyText: '无消费记录' }}
            />
        );
    };

    return (
        <Card
            title="我的历史记录"
            style={{ maxWidth: 1000, margin: '0 auto' }}
            headStyle={{ backgroundColor: '#f0f2f5', fontWeight: 'bold' }}
        >
            <Form
                form={form}
                layout="inline"
                onFinish={handleQuery}
                style={{ marginBottom: 24 }}
            >
                <Form.Item
                    name="idCard"
                    label="身份证号"
                    rules={[
                        { required: true, message: '请输入身份证号' },
                        { len: 18, message: '身份证号应为18位' }
                    ]}
                >
                    <Input
                        placeholder="请输入身份证号"
                        prefix={<UserOutlined />}
                        style={{ width: 300 }}
                        onPressEnter={() => form.submit()}
                    />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" loading={loading}>
                        查询
                    </Button>
                </Form.Item>
            </Form>

            {error && <div style={{ color: 'red', marginBottom: 20 }}>{error}</div>}

            {checkins.length > 0 ? (
                <Table
                    columns={checkinColumns}
                    dataSource={checkins}
                    rowKey="checkin_id"
                    pagination={{ pageSize: 5 }}
                    loading={loading}
                    bordered
                    expandable={{
                        expandedRowRender: (record) => (
                            <ExpandedConsumptionRow checkinId={record.checkin_id} />
                        ),
                        rowExpandable: (record) => record.checkin_id !== null,
                    }}
                    locale={{ emptyText: '无入住记录' }}
                />
            ) : (
                !loading && !error && (
                    <div style={{ textAlign: 'center', color: '#888' }}>
                        请输入身份证号并点击查询，查看您的入住和消费记录。
                    </div>
                )
            )}
        </Card>
    );
};

export default ClientHistory;